// import React from "React";
import { useEffect, useState } from 'react'
import { getAirplaneInfo, getFerrisTicket, getAirplaneRecord, buyFerrisTicket, getAirplane } from '../../../api/active'
import './index.less'
import { InfiniteScroll, Input, Modal, NoticeBar, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { GetUserInfo } from '../../../api/mine'
import appSdk from '../../../utils/app_sdk'
const menuItem = [
  { title: '梦境摩天轮', id: 1 },
  { title: '爱意摩天轮', id: 2 },
  { title: '摩天轮门票', id: 3 }
]
// 2：礼物 4：头像框 5：气泡框 6：进场特效
const giftType = {
  2: '礼物',
  4: '头像框',
  5: '气泡框',
  6: '进场特效'
}
export default function FerrisWheel() {
  const navigate = useNavigate()
  const [type, setType] = useState(1)
  const [buyNum, setBuyNum] = useState(1) // 装扮数量
  const [buyNum2, setBuyNum2] = useState(1) // 装扮数量
  const [rewardStatus, setRewardStatus] = useState(false)
  const [playing, setPlaying] = useState(false)
  const [ruleVisible, setRuleVisible] = useState(false)
  const [noDataVisible, setNoDataVisible] = useState(false)

  const [gifData, setGifData] = useState([])

  const [allData, setAllData] = useState([]) // 所有数据
  const [tickInfo, setTickInfo] = useState({ box_show_data: [], ticket_id: '', ticket_num: '', id: '' })
  const [userinfo, setUserinfo] = useState({ mizuan: 0 })
  const [saleItems, setsaleItems] = useState([])
  const initData = () => {
    Toast.show({ content: '加载数据...', icon: 'loading', duration: 0 })
    getAirplaneInfo({
      type: 3
    }).then((res) => {
      console.log(res.data)
      setAllData(res.data?.list || [])
      // setActiveInfo(res.data.list.concat(res.data.list))
      setTickInfo(res.data.list[type - 1 || 0])
      getFerrisTicket()
        .then((res) => {
          console.log(res)
          setsaleItems(res?.data || [])
        })
        .finally(() => {
          Toast.clear()
        })
    })
    GetUserInfo().then((res) => {
      setUserinfo(res.data)
    })
  }

  // 买票
  const buyTick = (idx) => {
    if (Number(userinfo.mizuan) >= Number(saleItems[idx].price) * (idx ? buyNum2 : buyNum)) {
      buyFerrisTicket({
        goods_id: saleItems[idx].id,
        nums: idx ? buyNum2 : buyNum
      }).then((res) => {
        console.log(res)
        Toast.show({ content: `恭喜您，获得${res?.data || 1}张门票` })
      })
    } else {
      setNoType('money')
      setNoDataVisible(true)
    }
  }

  useEffect(() => {
    initData()
  }, [type])

  // 抽奖
  const [noType, setNoType] = useState('tick')
  const checkBuy = (num) => {
    if (type === 2 ? Number(tickInfo.ticket_num) < num : Number(tickInfo.ticket_num) < num * 6) {
      setNoType('tick')
      setNoDataVisible(true)
    } else {
      toBuy(num)
    }
  }

  const [totalPrice, setTotalPrice] = useState(0) // 礼物总价值
  const toBuy = (num) => {
    if (rewardStatus) {
      setRewardStatus(false) // 已经开奖回到轮盘
    } else {
      if (!playing) {
        getAirplane({
          box_id: tickInfo.id,
          nums: num,
          type: 3
        })
          .then((res) => {
            setGifData(res?.data.reward_data)
            setTotalPrice(res.data?.price_count_nums || 0)
            setPlaying(true)
            initData()
            setTimeout(() => {
              setPlaying(false)
              setRewardStatus(true)
            }, 1800)
          })
          .catch((err) => {
            Toast.clear()
            Toast.show({
              content: err.msg
            })
          })
      } else {
        Toast.show({
          content: '等待抽奖结束～'
        })
      }
    }
  }

  const changeType = (num) => {
    if (playing) {
      Toast.show({
        content: '等待抽奖结束～'
      })
      return false
    }
    if (num < 3) {
      setTickInfo(allData[num - 1])
    }
    setType(num)
    setRewardStatus(false)
  }

  const [recordVisible, setRecordVisible] = useState(false)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [recordList, setRecordList] = useState([])
  const getRecordList = async () => {
    try {
      const res = await getAirplaneRecord({ page, type: 3 })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  useEffect(() => {
    if (recordVisible) {
      setPage(1)
      setHasMore(true)
      setRecordList([])
    }
  }, [recordVisible])

  return (
    <div className={`ferris_wrap wrap_${type}`}>
      <div className="ferris_nav">
        {menuItem.map((item) => (
          <div key={item.id} className={`item ${item.id === type ? 'active' : ''}`} onClick={() => changeType(item.id)}>
            <div className="icon"></div>
            <div className="txt ellipsis1">{item.title}</div>
          </div>
        ))}
      </div>
      <NoticeBar content={'理性参与游戏活动，禁止一切赌博性质行为，谨防上当受骗，杜绝违法犯罪，珍享游戏趣味。'} color="alert" icon={null} />
      <div className={`wheel_content content_${type} ${rewardStatus ? 'show_data' : ''}`}>
        {rewardStatus ? (
          <div className="data_list_reward">
            {gifData.map((item, idx) => (
              <div className="item" key={idx}>
                <img src={item.img} alt="" />
                <div className="name a ellipsis1">{item.name}</div>
                <div className="price a">
                  {item.price}
                  {window.baseConfig.coin_name}
                </div>
                {Number(item.nums) > 1 ? (
                  <div className="num">
                    <span>{item.nums}</span>
                  </div>
                ) : null}
              </div>
            ))}
          </div>
        ) : null}
        <div className="wheel_info">
          {rewardStatus ? (
            <div className="total_price">
              礼物总价值：{totalPrice}
              {window.baseConfig.coin_name}
            </div>
          ) : null}
          <div className="btns">
            <div className="left a" onClick={() => setRecordVisible(true)}>
              记录
            </div>
            <div className="right a" onClick={() => setRuleVisible(true)}>
              规则
            </div>
          </div>
          <div className={`wheel ${playing ? 'play' : ''}`}>
            <div className="data_list">
              {tickInfo?.box_show_data?.slice(0, 10)?.map((item, idx) => (
                <div className={`item item_${idx + 1}`}>
                  <img src={item.show_img} alt="" />
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="wheel_tit"></div>
        <div className="wheel_base">
          <div className="ticket_info">
            <div className="icon"></div>
            <div className="txt">摩天轮门票：{Number(tickInfo?.ticket_num) < 0 ? 0 : tickInfo?.ticket_num} 张</div>
            <div className="btn" onClick={() => changeType(3)}>
              <span>去获取</span>
            </div>
          </div>
          <div className="use_btns">
            <div className="btn" onClick={() => checkBuy(1)}></div>
            <div className="btn" onClick={() => checkBuy(10)}></div>
            <div className="btn" onClick={() => checkBuy(100)}></div>
          </div>
        </div>
        <div className="wheel_pice">
          {saleItems.map((item, idx) => (
            <div className="item">
              <div className="img">
                <img src={item.show_img} alt="" />
                <div className="send">
                  <span>{item?.gifts_note}</span>
                  {/* <span>赠</span><div className='icon' /><span>随机{idx ? '10-15' : '2-5'}张</span> */}
                </div>
              </div>
              <div className="name">
                {item?.type in giftType ? giftType[item?.type] : '头像框'}：{item.name}
              </div>
              <div className="price">
                <span>{item.price}</span>
                {window.baseConfig.coin_name}/天
              </div>
              <div className="ainput">
                <div
                  className="add a_btn"
                  onClick={() => {
                    !idx ? setBuyNum(buyNum > 1 ? +buyNum - 1 : 1) : setBuyNum2(buyNum2 > 1 ? +buyNum2 - 1 : 1)
                  }}
                >
                  -
                </div>
                <Input
                  onChange={(v) => {
                    if (+v > 100) {
                      !idx ? setBuyNum(100) : setBuyNum2(100)
                    } else {
                      !idx ? setBuyNum(Number(v).toFixed(0).replace(/^0+/, '')) : setBuyNum2(Number(v).toFixed(0).replace(/^0+/, ''))
                    }
                  }}
                  type="number"
                  value={!idx ? buyNum : buyNum2}
                  min={1}
                  max={100}
                />
                <div
                  className="down a_btn"
                  onClick={() => {
                    !idx ? setBuyNum(buyNum < 100 ? +buyNum + 1 : 100) : setBuyNum2(buyNum2 < 100 ? +buyNum2 + 1 : 100)
                  }}
                >
                  +
                </div>
              </div>
              <div className="btn" onClick={() => buyTick(idx)}>
                兑换
              </div>
            </div>
          ))}
        </div>
        {/* <div className="record">
					<div className="tit_icon">兑换记录</div>
				</div> */}
      </div>

      <Modal
        onClose={() => setNoDataVisible(false)}
        closeOnMaskClick={false}
        visible={noDataVisible}
        className=""
        content={
          <div className="no_money">
            <div className="tit">{noType === 'tick' ? '门票不足是否前往获取' : `${window.baseConfig.coin_name}不足是否前往充值`}</div>
            <div className="btns">
              <div className="btn a" onClick={() => setNoDataVisible(false)}>
                取消
              </div>
              <div
                className="btn b"
                onClick={() => {
                  setNoDataVisible(false)
                  if (noType === 'tick') {
                    setType(3)
                    setRewardStatus(false)
                    setGifData([])
                  } else {
                    // navigate('/recharge')
                    appSdk('jumpToRecharge')
                  }
                }}
              >
                确认
              </div>
            </div>
          </div>
        }
      />

      <Modal
        closeOnMaskClick={true}
        onClose={() => setRecordVisible(false)}
        visible={recordVisible}
        className="record_modal"
        destroyOnClose
        content={
          <div>
            <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
          </div>
        }
      />

      <Modal
        closeOnMaskClick={true}
        onClose={() => setRuleVisible(false)}
        visible={ruleVisible}
        className="record_modal"
        destroyOnClose
        content={
          <div className="record">
            <div className="title">活动规则&概率</div>
            <div className="list cont">
              <p>
                1、 每次参与“幸福摩天轮”活动需要花费{window.baseConfig.coin_name}{' '}
                购买限时头像框/限时进场特效获得随机数量的门票，消耗一定数量的即可乘坐摩天轮，每次乘坐摩天轮后，可获得随机道具奖励，获得的奖励道具可在"乘坐记录"里面查看。
              </p>
              <p>
                2、 "幸福摩天轮"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
                {window.baseConfig.coin_name}、现金、不可再次交易; 您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为。
              </p>
              <p>
                3、  利用漏洞或者是其他非法途径参与本活动，官方有权取消其活动参与资格。{window.baseConfig.package_name}
                有权清除活动中的非法数据。
              </p>
              <p>4、  活动如有任何疑问请联系{window.baseConfig.package_name}客服。</p>
              <p>
                5、  活动获得的所有虚拟道具及权益均不可进行转让、交易或变现，{window.baseConfig.package_name}
                官方有权对任何违规行为进行处理。
              </p>
              <p>在此活动中，APPLE不是赞助者，也没有以任何形式参与活动</p>
              <p className="t">奖品详情</p>
              <div className="con">
                <img src={tickInfo?.rule_img} alt="" />
              </div>
            </div>
          </div>
        }
      />
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      <div className="title">兑换记录</div>
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.id}>
            <div
              className="item"
              onClick={() => {
                if (item.id === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.id)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.id ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
